package com.cvte.sunkit.manage

import android.util.Log

/**
 *  @PackageName com.cvte.sunkit.manage
 *  @Description 内存异常数据的监听类，更新异常计数器和异常状态和阈值
 *  @Author lixu
 *  @Data 2023/7/19 09:33
 *  @Version 1.0
 */
object MemoryMonitor {
    private var mMemoryCount = 0 // 异常计数器
    private var mThresholdMemory = 500L // MB
    private var isAbnormal = false
    private const val TAG = "MemoryMonitor"
    private var mAbnormalCnt = 0

    /**
     * 对外方法，更新count的值
     */
    fun updateMemoryCount(memAvail: Long) {
        if (memAvail > mThresholdMemory) {
            subMemoryCount()
            Log.i(TAG, "内存异常计数器: $memAvail $mMemoryCount")
            if (mMemoryCount == 0) {
                isAbnormal = false
            }
        } else {
            addMemoryCount()
            Log.i(TAG, "内存异常计数器: $memAvail $mMemoryCount")
            if (mMemoryCount == 3) {
                isAbnormal = true
            }
        }
    }

    /**
     * 计数器加一
     */
    private fun addMemoryCount() {
        mMemoryCount = if (mMemoryCount < 3) (mMemoryCount + 1) else 3
    }

    /**
     * 计数器减一
     */
    private fun subMemoryCount() {
        mMemoryCount = if (mMemoryCount > 0) (mMemoryCount - 1) else 0
    }


    fun isAbnormal() = isAbnormal

    fun setThresholdMemory(threshold: Long) {
        mThresholdMemory = threshold
    }

    fun getThresholdMemory() = mThresholdMemory

    fun addAbnormalCnt() {
        mAbnormalCnt++
    }

    fun getAbnormalCnt(): Int = mAbnormalCnt

    fun resetAbnormalCnt() {
        mAbnormalCnt = 0
    }

}